
// @ts-ignore;
import React, { useState, useRef } from 'react';
// @ts-ignore;
import { Button } from '@/components/ui';
// @ts-ignore;
import { Camera, Image as ImageIcon, Wand2, ChevronLeft, ChevronRight } from 'lucide-react';

export default function Studio(props) {
  const {
    $w
  } = props;
  const [selectedImage, setSelectedImage] = useState(null);
  const [selectedStyle, setSelectedStyle] = useState(0);
  const [isGenerating, setIsGenerating] = useState(false);
  const scrollRef = useRef(null);
  const styles = [{
    id: 1,
    name: '水墨风格',
    icon: <Wand2 />,
    params: '笔触: 细腻, 墨色: 浓淡'
  }, {
    id: 2,
    name: '油画风格',
    icon: <Wand2 />,
    params: '笔触: 厚重, 色彩: 丰富'
  }, {
    id: 3,
    name: '像素风格',
    icon: <Wand2 />,
    params: '像素: 8-bit, 色彩: 鲜艳'
  }, {
    id: 4,
    name: '抽象风格',
    icon: <Wand2 />,
    params: '形态: 自由, 色彩: 大胆'
  }, {
    id: 5,
    name: '水彩风格',
    icon: <Wand2 />,
    params: '笔触: 柔和, 色彩: 透明'
  }];

  const handleImageUpload = e => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = event => {
        setSelectedImage(event.target.result);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleTakePhoto = () => {
    alert('调用相机功能');
  };

  const scrollLeft = () => {
    scrollRef.current.scrollBy({
      left: -200,
      behavior: 'smooth'
    });
  };

  const scrollRight = () => {
    scrollRef.current.scrollBy({
      left: 200,
      behavior: 'smooth'
    });
  };

  const handleGenerate = async () => {
    if (!selectedImage || !styles[selectedStyle]) return;
    setIsGenerating(true);
    try {
      const artworkData = {
        image: selectedImage,
        style_id: styles[selectedStyle].id,
        style_name: styles[selectedStyle].name,
        style_params: styles[selectedStyle].params,
        is_generating: true,
        title: `我的${styles[selectedStyle].name}作品`,
        description: `使用${styles[selectedStyle].name}风格创作`,
        created: new Date().toISOString(),
        user_id: $w.auth.currentUser?.userId || '',
        generation_status: 'processing'
      };
      
      const result = await $w.cloud.callDataSource({
        dataSourceName: 'artwork',
        methodName: 'wedaCreateV2',
        params: {
          data: artworkData
        }
      });

      setTimeout(async () => {
        await $w.cloud.callDataSource({
          dataSourceName: 'artwork',
          methodName: 'wedaUpdateV2',
          params: {
            data: {
              is_generating: false,
              generation_status: 'completed'
            },
            filter: {
              where: {
                _id: {
                  $eq: result.id
                }
              }
            }
          }
        });
        setIsGenerating(false);
        $w.utils.navigateTo({
          pageId: 'result',
          params: {
            artworkId: result.id
          }
        });
      }, 3000);
    } catch (error) {
      console.error('生成失败:', error);
      setIsGenerating(false);
    }
  };

  return (
    <div className="relative min-h-screen bg-gray-50">
      {/* 顶部标题 */}
      <div className="pt-8 pb-4 px-6">
        <h1 className="text-3xl font-bold text-purple-800">AI艺术创作</h1>
        <p className="text-gray-600 mt-2">上传照片并选择风格，生成您的专属艺术品</p>
      </div>

      {/* 照片上传区 */}
      <div className="flex flex-col items-center px-6 py-8">
        <div className="relative w-64 h-64 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden border-4 border-dashed border-purple-300">
          {selectedImage ? (
            <img src={selectedImage} alt="预览" className="w-full h-full object-cover" />
          ) : (
            <div className="text-center p-4">
              <ImageIcon className="mx-auto text-gray-400" size={48} />
              <p className="text-gray-500 mt-2">上传照片</p>
            </div>
          )}
        </div>

        <div className="flex space-x-4 mt-6">
          <label className="flex items-center justify-center px-4 py-2 bg-purple-600 text-white rounded-full cursor-pointer hover:bg-purple-700 transition">
            <input type="file" accept="image/*" className="hidden" onChange={handleImageUpload} />
            <ImageIcon className="mr-2" size={18} />
            相册选取
          </label>
          <button 
            onClick={handleTakePhoto} 
            className="flex items-center justify-center px-4 py-2 bg-pink-600 text-white rounded-full hover:bg-pink-700 transition"
          >
            <Camera className="mr-2" size={18} />
            拍照
          </button>
        </div>
      </div>

      {/* 风格选择器 */}
      <div className="px-6 py-4">
        <h2 className="text-xl font-semibold text-gray-800 mb-4">选择艺术风格</h2>
        <div className="relative">
          <button 
            onClick={scrollLeft} 
            className="absolute left-0 top-1/2 -translate-y-1/2 z-10 bg-white p-2 rounded-full shadow-md hover:bg-gray-100"
          >
            <ChevronLeft className="text-purple-600" />
          </button>
          
          <div 
            ref={scrollRef} 
            className="flex space-x-4 overflow-x-auto py-4 px-2 scrollbar-hide" 
            style={{ scrollSnapType: 'x mandatory' }}
          >
            {styles.map((style, index) => (
              <div 
                key={style.id} 
                onClick={() => setSelectedStyle(index)}
                className={`flex-shrink-0 w-48 p-4 rounded-xl cursor-pointer transition-all ${
                  selectedStyle === index ? 'bg-purple-100 border-2 border-purple-500' : 'bg-white border border-gray-200'
                }`}
                style={{ scrollSnapAlign: 'start' }}
              >
                <div className="flex items-center justify-center w-12 h-12 bg-purple-500 text-white rounded-full mx-auto">
                  {style.icon}
                </div>
                <h3 className="text-center font-medium mt-2">{style.name}</h3>
                <p className="text-xs text-gray-500 text-center mt-1">{style.params}</p>
              </div>
            ))}
          </div>

          <button 
            onClick={scrollRight} 
            className="absolute right-0 top-1/2 -translate-y-1/2 z-10 bg-white p-2 rounded-full shadow-md hover:bg-gray-100"
          >
            <ChevronRight className="text-purple-600" />
          </button>
        </div>
      </div>

      {/* 生成按钮 */}
      <div className="px-6 py-8">
        <button 
          onClick={handleGenerate} 
          disabled={!selectedImage || isGenerating}
          className={`w-full py-4 rounded-xl text-white font-bold text-lg flex items-center justify-center ${
            !selectedImage || isGenerating ? 'bg-gray-400 cursor-not-allowed' : 'bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 shadow-lg'
          }`}
        >
          {isGenerating ? '创作中...' : (
            <>
              <Wand2 className="mr-2" />
              开始创作
            </>
          )}
        </button>
      </div>

      {/* 水墨扩散加载动画 */}
      {isGenerating && (
        <div className="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50">
          <div className="text-center">
            <div className="relative w-32 h-32">
              <div className="absolute inset-0 rounded-full bg-white opacity-20 animate-ping"></div>
              <div 
                className="absolute inset-2 rounded-full bg-white opacity-30 animate-ping" 
                style={{ animationDelay: '0.2s' }}
              ></div>
              <div 
                className="absolute inset-4 rounded-full bg-white opacity-40 animate-ping" 
                style={{ animationDelay: '0.4s' }}
              ></div>
              <div 
                className="absolute inset-6 rounded-full bg-white opacity-50 animate-ping" 
                style={{ animationDelay: '0.6s' }}
              ></div>
            </div>
            <p className="text-white mt-6 text-xl">AI正在创作您的艺术品...</p>
          </div>
        </div>
      )}
    </div>
  );
}
